package com.tiandang.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tiandang.core.model.Manager;
import tiandang.core.model.OrderInfo;
import tiandang.core.model.Promo;
import tiandang.core.model.PromoProduct;
import tiandang.core.response.CommonReturnType;
import tiandang.core.service.ManagerService;
import tiandang.core.service.OrderService;
import tiandang.core.service.PromoProductService;
import tiandang.core.service.PromoService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wechat/detail")
public class DetailController {

  @Autowired
  private ManagerService managerService;

  @Autowired
  private PromoService promoService;

  @Autowired
  private PromoProductService promoProductService;

  @Autowired
  private OrderService orderService;

  @GetMapping("/getPromoDetail")
  public CommonReturnType getPromoDetail(@RequestParam(value = "promoId") Integer promoId,
                                         @RequestParam(value = "managerId", required = false) Integer managerId) {
    Map<String, Object> resultMap = new HashMap<>();

    if (managerId != null) {
      //获取团长信息
      Manager manager = managerService.getManagerById(managerId);
      resultMap.put("manager", manager);
    }

    //获取团购信息
    Long now = new Date().getTime();
    Promo promo = promoService.getPromoById(promoId);
    if (promo.getStartTimestamp() > now) {
      promo.setStatus(0); //0未开始
    } else if (promo.getEndTimestamp() < now) {
      promo.setStatus(2); //2已结束
    } else {
      promo.setStatus(1); //1进行中
    }

    //获取此次团购所有商品
    List<PromoProduct> productList = promoProductService.getListByPromoId(promoId);

    //获取此次团购下单的用户
    List<OrderInfo> orderList = orderService.getListByPromoId(promoId);

    resultMap.put("systemTime", new Date().getTime());
    resultMap.put("promo", promo);
    resultMap.put("productList", productList);
    resultMap.put("orderList", orderList);
    return CommonReturnType.success(resultMap);
  }
}
